package com.friends.library.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.friends.library.Dto.BookRegistration;
import com.friends.library.persistence.HibernateUtil;

public class BookRegistration1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     * @author HAVE A NICE DAY
     */
    public BookRegistration1() {
        super();
        // TODO Auto-generated constructor stub
    }


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//Hitcounter for this servlet
		ServletContext context = getServletContext();
		Integer count = (Integer) context.getAttribute("hitcount");
		if (count == null) {

			count = 1;

		} else {
			
						count++;
		}
		context.setAttribute("hitcount", count);
		//getting values from jsp page
		String bname=request.getParameter("bookname");
		String aname=request.getParameter("authorname");
		String status=request.getParameter("status");
		Double price=Double.parseDouble(request.getParameter("price"));
	
		//making connection with database through hibernate
		try{
			
		Session session=HibernateUtil.getSessionFactory().openSession();
		Transaction transaction=session.beginTransaction();
		
		//creating object for pojo(plain old java object)for storing into database
		
		BookRegistration bookRegistration=new BookRegistration();
		bookRegistration.setBookname(bname);
		bookRegistration.setAuthorname(aname);
		bookRegistration.setDate(new Date());
		bookRegistration.setStatus(status);
		bookRegistration.setPrice(price);
		
		
		session.save(bookRegistration);
		transaction.commit();
		session.close();
		}
		catch (Exception e) {
			// TODO: handle exception
		System.err.println("the error is:"+e);
		}
		//for displaying weather success or not
		
		response.setContentType("text/html");
		PrintWriter out=response.getWriter();
		
		out.println("<html>");
		out.println("<head>");
		out.println("</head>");
		out.println("<body>");
		out.println("<h1>");
		out.println("New Book Registration is Saved in to Database");
		out.println("</h1>");
		out.println("<a href='newbookregistration.jsp'>Back</a>");
		out.println("Hit count of this page is:"+count);
		out.println("</body>");
		out.println("</html>");
		
	}

}
